import { AppDataSource } from "./data-source"
import { Author } from "./entity/Author";
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetaData";
import { User } from "./entity/User"

AppDataSource.initialize().then(async () => {

  // 创建 photo
  const photo = createPhoto();
  const photo2 = createPhoto();
  const author = createAuthor([photo, photo2]);
  // 创建 photo metadata
  const metadata = createPhotoMetaData(photo);
  // const metadata2 = createPhotoMetaData(photo2);

  // console.log(metadata);
  const metadataRepository = AppDataSource.manager.getRepository(PhotoMetadata);
  await metadataRepository.save(metadata);
  // await metadataRepository.save(metadata2);

  const authorRepository = AppDataSource.manager.getRepository(Author);
  await authorRepository.save(author);

  console.log("Photo has been saved")

  const authors = await authorRepository.find({ relations: ['photos'] });
  console.log("Loaded authors: ", authors)

  // const photos = await photoRepository.find({ relations: ['metadata'] });
  // console.log("Loaded photos: ", photos)

  // const metadatas = await metadataRepository.find({ relations: ['photo'] });
  // console.log("Loaded metadatas: ", metadatas)


  console.log("Here you can setup and run express / fastify / any other framework.")

}).catch(error => console.log(error))

function createPhoto() {
  // 创建 photo
  const photo = new Photo();
  photo.name = "Me and Bears";
  photo.description = "I am near polar bears";
  photo.filename = "photo-with-bears.jpg";
  photo.isPublished = true;
  photo.views = 1;
  return photo;
}

function createPhotoMetaData(photo: Photo) {
  // 创建 photo metadata
  const metadata = new PhotoMetadata();
  metadata.height = 640;
  metadata.width = 480;
  metadata.compressed = true;
  metadata.comment = "cybershoot";
  metadata.orientation = "portrait";
  metadata.photo = photo;
  return metadata;
}

function createAuthor(photos: Photo[] = []) {
  const author = new Author();
  author.name = 'test author';
  author.photos = photos;
  return author;
}
